package menu.lt.pers.menu.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.google.gson.Gson;
import menu.lt.pers.menu.Bean.NODATA;
import menu.lt.pers.menu.Bean.ResultByClassIdBean;
import menu.lt.pers.menu.Bean.ResultByNameBean;
import menu.lt.pers.menu.R;
import menu.lt.pers.menu.ResultByName;
import menu.lt.pers.menu.dao.ResourceDao;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class RecipeListByNameViewAdapter extends BaseAdapter {
    private List<ResultByNameBean.ResultBean.ListBean> list;
    private HashMap<Integer,Bitmap> bitmapcache = new HashMap<>();
    private List<ResultByNameBean.ResultBean.ListBean> recipes;
    private List<ResultByNameBean.ResultBean.ListBean.MaterialBean> materials;private int numOfOnce;
    private int num;
    private Context context;
    private LayoutInflater inflater;
    private String content;

    public RecipeListByNameViewAdapter(Context context,String content) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.content = content;
        num = 40;
        bitmapcache = new HashMap<>();
        list = new ArrayList<ResultByNameBean.ResultBean.ListBean>();
        new GetData().execute(content,num);
    }
    @Override
    public int getCount() {
        return this.list.size();
    }

    public void updateView(){
        notifyDataSetChanged();
    }
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.classactivity_listview_resource, null);
            holder = new Holder();
            holder.imageView = convertView.findViewById(R.id.imageView);
            holder.tv_recipematerial = convertView.findViewById(R.id.tv_recipematerial);
            holder.tv_recipename = convertView.findViewById(R.id.tv_recipename);
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }
//        new GetBimap().execute(list.get(position).getPic(),position);
//        if (bitmapcache.get(position)!=null){
//            holder.imageView.setImageBitmap(bitmapcache.get(position));
//        } else {
//            holder.imageView.setImageResource(R.drawable.timg);
//        }
        new GetBimap().execute(list.get(position).getPic(),position);
        if (bitmapcache.get(position)!=null){
            holder.imageView.setImageBitmap(bitmapcache.get(position));
        } else {
            holder.imageView.setImageResource(R.drawable.timg);
        }
        holder.tv_recipename.setText(list.get(position).getName());
        materials = list.get(position).getMaterial();
        String materialstr = "";
        for(int i=0;i<materials.size();i++){
            materialstr = materialstr + materials.get(i).getMname()+",";
        }
        holder.tv_recipematerial.setText(materialstr.substring(0,materialstr.length()-1));
        return convertView;
    }
    public class Holder {
        private ImageView imageView;
        public TextView tv_recipename;
        public TextView tv_recipematerial;
    }

    class GetBimap extends AsyncTask {
        private int position;
        @Override
        protected Bitmap doInBackground(Object[] params) {
            position = (int) params[1];
            if (bitmapcache.get(position)==null){
                String uripath = (String) params[0];
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(5000, TimeUnit.SECONDS)
                        .readTimeout(5000,TimeUnit.SECONDS)
                        .build();
                Request request = new Request.Builder()
                        .url(uripath)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()){
                        InputStream inputStream = response.body().byteStream();//得到图片的流
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        return bitmap;
                    }else {
                        return null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o!=null && bitmapcache.get(position)==null){
                Bitmap bitmap = (Bitmap) o;
                bitmapcache.put(position,bitmap);
                notifyDataSetChanged();
            }
        }
    }
    class GetData extends AsyncTask{

        @Override
        protected ResultByNameBean doInBackground(Object[] params) {
            String uripath = ResourceDao.findRecipeByName +
                    "keyword="+params[0]+
                    "&num="+params[1]+
                    "&appkey="+ResourceDao.appkey;
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(5000, TimeUnit.SECONDS)
                    .readTimeout(5000,TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(uripath)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()){
                    String result = response.body().string();
                    Gson gson = new Gson();
                    ResultByNameBean resultByNameBean;
                    try{
                        resultByNameBean = gson.fromJson(result,ResultByNameBean.class);
                        return resultByNameBean;
                    } catch (com.google.gson.JsonSyntaxException e){
                        NODATA error = gson.fromJson(result,NODATA.class);
                        resultByNameBean = new ResultByNameBean();
                        resultByNameBean.setStatus(Integer.valueOf(error.getStatus()));
                        resultByNameBean.setMsg(error.getMsg());
                        return resultByNameBean;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            ResultByNameBean resultByNameBean = (ResultByNameBean) o;
            if (resultByNameBean!=null){
                if (resultByNameBean.getStatus() == 0){
                    list = resultByNameBean.getResult().getList();
                    updateView();
                } else if (resultByNameBean.getStatus() == 205){
                    Toast.makeText(context,"查无此物",Toast.LENGTH_SHORT).show();
                }

            }
        }
    }

}
